class Milestone < ActiveRecord::Base
  belongs_to :project, :dependent => :destroy
  
  has_many :activities
  has_many :responsibles, :through => :activities, :class_name => "User", :foreign_key => "responsible_id", :group => "responsible_id"
  has_many :comments, :as => :commentable
  
  validates_presence_of :title, :due
  
  validate :date_must_not_be_in_the_past, :if => :due_changed?
  
  def date_must_not_be_in_the_past
    errors.add :due, I18n.t(:date_must_not_be_in_the_past, :scope => [:milestone, :messages, :errors]) if Date.today > self.due
  end
  
  named_scope :with_activities, :joins => "LEFT JOIN activities on activities.milestone_id = milestones.id", 
                                :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                                :group => "milestones.id"
  
  named_scope :completed, :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :having => "activities_quantity = completed"

  named_scope :pending,   :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :having => "activities_quantity > completed"
                          
  named_scope :late,      :joins => :activities, 
                          :select => "milestones.*, count(activities.id) as activities_quantity, count(activities.completed_at) as completed",
                          :group => "milestones.id",
                          :conditions => ["milestones.due < ?", Date.current],
                          :having => "activities_quantity > completed"
                          
  named_scope :reminder_not_sent, :conditions => {:reminder_sent => false}
  
  def to_param
    "#{id}#{title.gsub(/[^a-z0-9]+/i, '-')}".downcase
  end
  
  def late?
    Date.current > due
  end
  
  def progress
    activities.completed.size.to_f / activities.size * 100 if activities.size > 0
  end
  
  def to_s
    title
  end
  
  
  has_many :logs, :as => :loggable
  
  after_create :log_creation
  after_update :log_update
  after_destroy :log_delete
  
  def log_creation
    logs.new(:project => project, :action => "created", :user_id => Thread.current[:user_id]).save
  end
  
  def log_update
    logs.new(:project => project, :action => "changed", :user_id => Thread.current[:user_id]).save
  end
  
  def log_delete
    logs.new(:project => project, :action => "deleted", :user_id => Thread.current[:user_id]).save
  end

end
